package com.bluesky.plum.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.bluesky.plum.domain.repository.FooEntity;

/**
 * another Bean utils
 * 
 * @author hz00260
 * 
 */
public class BeanUtils {

	/**
	 * get all fields, including it's super class, until the root class(Object,
	 * not included).
	 * 
	 * @param clazz
	 * @return
	 */
	public static List<BeanField> getFields(Class clazz) {
		List<BeanField> beanFields = new ArrayList<BeanField>();

		Class nextClass = clazz;
		while (nextClass != Object.class) {
			List<BeanField> beanFields2 = getDeclaredFields(nextClass);
			beanFields.addAll(beanFields2);

			nextClass = nextClass.getSuperclass();
		}

		return beanFields;
	}

	/**
	 * only the declared field, any super class field not included.
	 * @param clazz
	 * @return
	 */
	public static List<BeanField> getDeclaredFields(Class clazz) {
		List<BeanField> beanFields = new ArrayList<BeanField>();

		Field[] fields = clazz.getDeclaredFields();
		for (Field f : fields) {
			BeanField bf = new BeanField();
			bf.name = f.getName();

			Method m;

			String s;
			try {
				s = "get" + makeFirstCharCapital(f.getName());
				m = clazz.getMethod(s, null);
				bf.getter = s;
			} catch (SecurityException e) {
				// it is not a public method
				// e.printStackTrace();
			} catch (NoSuchMethodException e) {

				try {
					s = "is" + makeFirstCharCapital(f.getName());
					m = clazz.getMethod(s, null);
					bf.getter = s;
				} catch (SecurityException e1) {

					// e1.printStackTrace();
				} catch (NoSuchMethodException e1) {

					// e1.printStackTrace();
				}
			}

			try {
				s = "set" + makeFirstCharCapital(f.getName());
				m = clazz.getMethod(s, f.getType());
				bf.setter = s;
			} catch (SecurityException e1) {

				// e1.printStackTrace();
			} catch (NoSuchMethodException e1) {

				// e1.printStackTrace();
			}

			beanFields.add(bf);

		}
		return beanFields;
	}

	private static String makeFirstCharCapital(String s) {
		return s.substring(0, 1).toUpperCase() + s.substring(1);
	}

	public static void main(String[] args) {
		System.out.println(BeanUtils.makeFirstCharCapital("abc"));

		// Employee emp = new Employee();
		List<BeanField> list = getFields(FooEntity.class);
		for (BeanField bf : list) {
			System.out.println(bf);
		}
	}
}
